package com.ruoyi.basic.controller;

import com.ruoyi.api.system.utils.ShiroUtils;
import com.ruoyi.basic.domain.BasicAppoint;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.service.IBasicAppointService;
import com.ruoyi.basic.service.IBasicUserService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 员工图片Controller
 * 
 * @author ruoyi
 * @date 2021-12-07
 */
@Controller
@RequestMapping("/basic/appoint")
public class BasicAppointController extends BaseController
{
    private String prefix = "basic/appoint";

    @Autowired
    private IBasicAppointService basicAppointService;

    @Autowired
    private IBasicUserService basicUserService;

    @RequiresPermissions("basic:appoint:view")
    @GetMapping()
    public String appoint()
    {
        return prefix + "/appoint";
    }

    /**
     * 查询员工图片列表
     */
    @RequiresPermissions("basic:appoint:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BasicAppoint basicAppoint)
    {
        startPage();
        List<BasicAppoint> list = basicAppointService.selectBasicAppointList(basicAppoint);
        return getDataTable(list);
    }

    /**
     * 新增员工图片
     */
    @GetMapping("/add/{userId}")
    public String add(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        BasicUser user = basicUserService.selectBasicUserById(userId);
        mmap.put("user", user == null ? new BasicUser() : user);
        return prefix + "/add";
    }

    /**
     * 新增保存员工图片
     */
    @RequiresPermissions("basic:appoint:add")
    @Log(title = "员工图片", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file, BasicAppoint basicAppoint) {
        BasicUser basicUser = basicUserService.selectBasicUserById(basicAppoint.getUserId());
        try{
            if(!file.isEmpty()) {
                String docFile = FileUploadUtils.upload(RuoYiConfig.getUploadPath() + "/" + basicUser.getName(), file, false);
                basicAppoint.setDocFile(docFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return error("图片上传失败");
        }
        basicAppoint.setCreateBy(ShiroUtils.getLoginName());
        return success(basicAppointService.insertBasicAppoint(basicAppoint));
    }

    /**
     * 修改员工图片
     */
    @GetMapping("/edit/{appointId}")
    public String edit(@PathVariable("appointId") Long appointId, ModelMap mmap)
    {
        BasicAppoint basicAppoint = basicAppointService.selectBasicAppointByAppointId(appointId);
        mmap.put("basicAppoint", basicAppoint);
        return prefix + "/edit";
    }

    /**
     * 修改保存员工图片
     */
    @RequiresPermissions("basic:appoint:edit")
    @Log(title = "员工图片", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam(required = false) MultipartFile file, BasicAppoint basicAppoint)
    {
        try {
            BasicUser basicUser = basicUserService.selectBasicUserById(basicAppoint.getUserId());
            if(!file.isEmpty()) {
                BasicAppoint old = basicAppointService.selectBasicAppointByAppointId(basicAppoint.getAppointId());
                FileUtils.deleteFile(RuoYiConfig.getProfile() + StringUtils.substringAfter(old.getDocFile(), Constants.RESOURCE_PREFIX));

                String docFile = FileUploadUtils.upload(RuoYiConfig.getUploadPath() + "/" + basicUser.getName(), file, false);
                basicAppoint.setDocFile(docFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return error("图片上传失败");
        }
        basicAppoint.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(basicAppointService.updateBasicAppoint(basicAppoint));
    }

    /**
     * 删除员工图片
     */
    @RequiresPermissions("basic:appoint:remove")
    @Log(title = "员工图片", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        for(Long id : Convert.toLongArray(ids)){
            BasicAppoint basicAppoint = basicAppointService.selectBasicAppointByAppointId(id);
            FileUtils.deleteFile(RuoYiConfig.getProfile() + StringUtils.substringAfter(basicAppoint.getDocFile(), Constants.RESOURCE_PREFIX));
        }
        return toAjax(basicAppointService.deleteBasicAppointByAppointIds(ids));
    }

    /**
     * 导出员工图片
     */
    @RequiresPermissions("basic:appoint:download")
    @Log(title = "员工图片", businessType = BusinessType.EXPORT)
    @GetMapping( "/download")
    public void download(String appointIds, HttpServletResponse response) throws Exception
    {
        List<BasicAppoint> imageList = basicAppointService.selectBasicAppointListByAppointIds(appointIds);
        String strZipPath = RuoYiConfig.getDownloadPath() + System.currentTimeMillis() + ".zip";
        ZipOutputStream out = null;
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try{
            out = new ZipOutputStream(new FileOutputStream(strZipPath));
            ServletOutputStream outputStream = response.getOutputStream();
            for(BasicAppoint basicAppoint : imageList) {
                String downloadPath = RuoYiConfig.getProfile() + StringUtils.substringAfter(basicAppoint.getDocFile(), Constants.RESOURCE_PREFIX);
                // 下载名称
                String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
                out.putNextEntry(new ZipEntry(downloadName));
                fis = new FileInputStream(new File(downloadPath));
                byte[] b = new byte[1024];
                int length;
                while ((length = fis.read(b)) > 0)
                {
                    out.write(b, 0, length);
                }
                out.closeEntry();
            }
            out.close();
            bis = new BufferedInputStream(new FileInputStream(strZipPath));
            FileCopyUtils.copy(bis, outputStream);
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            IOUtils.close(bis);
            IOUtils.close(fis);
            IOUtils.close(out);
        }
        FileUtils.deleteFile(strZipPath);
    }
}
